
import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/token.js'
// import Login from '../views/Login'
// import Home from '@/views/Home'
// import Layout from '@/views/layout'
// import User from '@/views/User'
// import Search from '@/Search'
// import SearchResult from '@/Search/SearchResult.vue'
// import ArticleDetail from '@/views/ArticleDetail'
// import userEdit from '@/views/User/userEdit.vue'
// import Chat from '@/views/Chat'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/layout/home'
  },
  {
    path: '/Search',
    component: () => import(/* webpackChunkName:"Search" */'@/Search/index.vue')
  },
  {
    path: '/userEdit',
    component: () => import(/* webpackChunkName:"userEdit" */'@/views/User/userEdit.vue')
  },
  {
    path: '/SearchResult/:kw',
    component: () => import(/* webpackChunkName:"SearchResult" */'@/Search/SearchResult.vue')
  },
  {
    path: '/login',
    component: () => import(/* webpackChunkName:"Login" */'../views/Login'),
    // 路由独享守卫
    beforeRouteEnter (to, from, next) {
      if (getToken()?.length > 0 && to.path === '/login') { // vuex里有token(代表登录过, 但是一定要注意过期和主动退出要先清除vuex和本地的token, 让其跳转登录页)
        // next(false) // 留在原地 /什么都不写
        next('/layout/home')
        // 手机app里没有地址栏,你是不能破坏跳转的过程的
      } else {
        next() // 其他情况都放行
      }
    }
  },
  {
    path: '/ArticleDetail',
    component: () => import(/* webpackChunkName:"ArticleDetail" */'@/views/ArticleDetail')
  },
  {
    path: '/chat',
    component: () => import(/* webpackChunkName:"chat" */'@/views/Chat')
  },
  {
    path: '/layout',
    component: () => import(/* webpackChunkName:"layout" */'@/views/layout'),
    children: [
      {
        path: 'home',
        component: () => import(/* webpackChunkName:"home" */'@/views/Home'),
        meta: {
          scrollT: 0 // 保存首页离开时,滚动的位置上
        }
      },
      {
        path: 'user',
        component: () => import(/* webpackChunkName:"user" */'@/views/User')
      }

    ]
  }

]

const router = new VueRouter({
  routes
})

// 路由 - 全局前置守卫(在路由发生跳转前 执行此函数)
// 此函数可以决定路由是否跳转/取消/ 强制切换到别的路由
router.beforeEach((to, from, next) => {
  // 需求 如果你已经登录了,不要切换到登录页面
  if (getToken()?.length > 0 && to.path === '/login') {
    next(false) // 留在原地 /什么都不写
  } else {
    next() // 其他请款都放行
  }
})

export default router
